package com.qhgrain.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.AppBusinessTypeEnum;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.service.ApplicationService;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.AppVo;
import com.qhgrain.app.vo.PairVo;
import com.qhgrain.gway.util.HttpUtil;

@Controller
@RequestMapping("/application")
public class ApplicationController {

	private static Logger LOG = LoggerFactory.getLogger(ApplicationController.class);
	@Autowired
	private ApplicationService applicationServiect;
	static String serverUrl;
	static {
		serverUrl = ConfigUtil.getProperties(UrlEnum.APP)+"/application";
	}
	
//	@RequiresPermissions({"common-service-app:query"} )
	@RequestMapping(value="/list")
	public String list(){
		return "application/application_list";
	}
	
	
	@RequestMapping(value="/list/table")
	public String queryApplicationsForTable(HttpServletRequest request,Model model,String appCode,String appName,String pageNo,String pageSize){
		
		if(StringUtils.isEmpty(pageNo)){
			pageNo="1";
		}
		if(StringUtil.isBlank(pageSize)){
			pageSize = "10";
		}
		Map<String,Object> map = new HashMap<String,Object>();
		
		map.put("pageNum", pageNo);
		map.put("pageSize", pageSize);
		
		if(StringUtil.isNotBlank(appName)){
			map.put("appName", appName);
		}
		if(StringUtil.isNotBlank(appCode)){
			map.put("appCode", appCode);
		}
		
		String requestVo;
		PageBean<AppVo> pageBean = new PageBean<AppVo>(Integer.parseInt(pageNo),Integer.parseInt(pageSize));;
		try {
			requestVo = HttpUtil.postFormParams(serverUrl,"/query/condition", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);
			
			if("200".equals(voJson.getString("state"))){
				pageBean.setData(JSONArray.parseArray(voJson.getString("data"),AppVo.class));
			}else{
				LOG.error("应用分页查询，api失败。。。"+voJson);
			}
			
			String countVo = HttpUtil.postFormParams(serverUrl,"/query/condition/count", map);
			JSONObject countJson = JSONObject.parseObject(countVo);
			
			if("200".equals(voJson.getString("state"))){
				pageBean.setTotalCount(countJson.getIntValue("data"));
			}else{
				LOG.error("应用查询总数，api失败。。。"+voJson);
			}
			
		} catch (Exception e) {
			LOG.error("应用分页查询查询出错。。。",e);
		}
		model.addAttribute("pageBean", pageBean);
		
		return "application/application_list_table";
	}
	
	@RequestMapping(value="/check/appcode")
	@ResponseBody
	public JSONObject findByAppCode(Model model, String appCode){
		JSONObject result = new JSONObject();
		try {
			if(StringUtil.isBlank(appCode)){
				result.put("code", "fail");
				result.put("msg", "应用编码不能为空");
			}else{
				AppVo app = this.applicationServiect.findByAppCode(appCode);
				if(app != null){
					result.put("code", "exist");
				}else{
					result.put("code", "notexist");
				}
			}
		} catch (Exception e) {
			LOG.error("根据应用编码查询对象信息系统出错");
			result.put("code", "fail");
		}
		return result;
	}
	
	@RequestMapping(value="/add")
	public String addPage(Model model){
		model.addAttribute("app", new JSONObject());
		model.addAttribute("appTypeList", AppBusinessTypeEnum.getAll());
		return "application/application_edit";
	}
	
	@RequestMapping(value="/edit/{id}")
	public String editPage(Model model,@PathVariable String id){
		JSONObject app = new JSONObject();
		try {
			String vo = HttpUtil.get(serverUrl+"/get/"+id, new HashMap<String,String>());
			JSONObject voJson = JSONObject.parseObject(vo);
			if("200".equals(voJson.getString("state"))){
				app = voJson.getJSONObject("data");
			}else{
				LOG.error("修改应用信息，从api获取对象信息失败..."+voJson.getString("exceptionMsg"));
			}
			
		} catch (Exception e) {
			LOG.error("修改应用，获取该应用信息时失败..."+e.getMessage());
		}
		model.addAttribute("app", app);
		model.addAttribute("appTypeList", AppBusinessTypeEnum.getAll());
		return "application/application_edit";
	}
	
	@RequestMapping(value="/detail/{id}")
	public String detailPage(Model model,@PathVariable String id){
		JSONObject app = new JSONObject();
		try {
			String vo = HttpUtil.get(serverUrl+"/get/"+id, new HashMap<String,String>());
			JSONObject voJson = JSONObject.parseObject(vo);
			if("200".equals(voJson.getString("state"))){
				app = voJson.getJSONObject("data");
			}else{
				LOG.error("查看应用详情，从api获取对象信息失败..."+voJson.getString("exceptionMsg"));
			}
			
		} catch (Exception e) {
			LOG.error("查看应用详情，获取该应用信息时失败..."+e.getMessage());
		}
		model.addAttribute("app", app);
		model.addAttribute("appTypeList", AppBusinessTypeEnum.getAll());
		return "application/application_detail";
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public JSONObject delete(Model model, String ids){
		JSONObject result = new JSONObject();
		if(StringUtil.isBlank(ids)){
			result.put("code", "0");
			result.put("msg", "应用id不能为空");
		}else{
			
			try {
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("ids", ids);
				String vo = HttpUtil.postFormParams(serverUrl, "/delete", paramMap);
				JSONObject voJson = JSONObject.parseObject(vo);
				if("200".equals(voJson.getString("state"))){
					result.put("code", "success");
					result.put("msg", "成功");
				}else{
					result.put("code", "fail");
					result.put("msg", "系统出错，删除失败!");
					LOG.error("删除应用,api失败..."+voJson);
				}
			} catch (Exception e) {
				LOG.error("删除应用，系统出错....ids="+ids,e);
				result.put("code", "fail");
				result.put("msg", "系统出错");
			}
		}
		
		return result;
	}
	@RequestMapping(value="/save")
	@ResponseBody
	public JSONObject save(Model model,String id,String appName,String businessType,String appUrl,
			String iconClass,String appCode,String appOrder,String description){
		JSONObject result = new JSONObject();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("appName", appName);
		map.put("businessType", businessType);
		map.put("appUrl", appUrl);
		map.put("iconClass", iconClass);
		map.put("appCode", appCode);
		map.put("appOrder", appOrder);
		map.put("description", description);
		
		try {
			String vo ;
			if(StringUtil.isNotBlank(id)){
				//修改
				map.put("id", id);
				vo = HttpUtil.postFormParams(serverUrl, "/update", map);
			}else{
				vo = HttpUtil.postFormParams(serverUrl, "/add", map);
			}
			JSONObject voJson = JSONObject.parseObject(vo);
			if("200".equals(voJson.getString("state"))){
				result.put("code", "success");
			}else{
				LOG.error("保存应用信息，从api失败..."+voJson);
				result.put("code", "fail");
			}
		} catch (Exception e) {
			LOG.error("保存应用信息系统出错..."+map,e);
			result.put("code", "fail");
		}
		
		return result;
	}
	
	@RequestMapping(value="/get/all")
	@ResponseBody
	public JSONObject getAll(Model model){
		JSONObject result = new JSONObject();
			
		try {
			String vo = HttpUtil.get(serverUrl+"/get/all", new HashMap<String,String>());
			JSONObject voJson = JSONObject.parseObject(vo);
			if("200".equals(voJson.getString("state"))){
				result.put("code", "success");
				result.put("msg", "成功");
				
				JSONArray array = voJson.getJSONArray("data");
				List<PairVo> list = new ArrayList<PairVo>();
				JSONObject o = null;
				for(int i = 0;i<array.size();i++){
					o = array.getJSONObject(i);
					list.add(new PairVo(o.getString("id"),o.getString("appName")));
				}
				result.put("data", list);
			}else{
				result.put("code", "fail");
				result.put("msg", "系统出错，删除失败!");
				LOG.error("删除应用,api失败..."+voJson);
			}
		} catch (Exception e) {
			LOG.error("删除应用，系统出错....",e);
			result.put("code", "fail");
			result.put("msg", "系统出错");
		}
		
		return result;
	}
	
	
}
